package com.javasea.schedule.asynctask.controller;

import com.javasea.schedule.asynctask.AsyncTaskManager;
import com.javasea.schedule.asynctask.entity.TaskInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "/api/v1/asynctask")
public class AsyncTaskController {
    //注入异步任务管理器
    @Autowired
    AsyncTaskManager asyncTaskManager;

    /**
     * http://localhost:8080/api/v1/asynctask/startTask
     * @return
     */
    @RequestMapping(value = "/startTask", method = RequestMethod.GET)
    public Object startAsyncTask() {
        //调用任务管理器中的submit去提交一个异步任务
        TaskInfo taskInfo = asyncTaskManager.submit(() -> {
            System.out.println("_____开始执行_____");
            try {
                //模拟异步，睡眠6秒
                Thread.sleep(12000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("_____执行结束_____");
        });
        return taskInfo;
    }

    @RequestMapping(value = "/getTaskStatus/{taskId}", method = RequestMethod.GET)
    public Object getTaskStatus(@PathVariable("taskId") String taskId) {
        return asyncTaskManager.getTaskInfo(taskId);
    }
}
